package com.cqu.lpss.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cqu.lpss.pojo.Result;
import com.cqu.lpss.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    //目标资源方法运行前运行，返回true，放行；返回false，不放行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (HttpMethod.OPTIONS.matches(request.getMethod())) {
            // 对于OPTIONS预检请求，直接放行
            return true;
        }
//      1.获取请求url
        String url = request.getRequestURI().toString();
        log.info("请求的url:{}",url);
        if(url.contains("login")||url.contains("register")){
            log.info("登录操作，放行......");
            return true;
        }
//        String jwt = request.getHeader("Authorization");
        String authorizationHeader = request.getHeader("Authorization");

        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            // 无令牌或格式错误，返回401 Unauthorized
            log.info("请求头token为空，返回未登录错误信息");
            Result error = Result.erro("NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }

        String jwt = authorizationHeader.substring("\"Bearer ".length());
        jwt = jwt.replaceAll("^\"|\"$", "");
        log.info("jwt:{}",jwt);
//        eyJhbGciOiJIUzI1NiJ9.eyJjb25JbmRleCI6MSwibmFtZSI6IuW8oOS4iSIsImNvbklkIjoiNzEwMTEyMTk5MDDiha0xMjM0NVgiLCJleHAiOjE3MTI4MTA1NjV9.uhDO80b7gavDWhdkSxpH5crvmk48e8gGD67d5AswvWo
//        eyJhbGciOiJIUzI1NiJ9.eyJjb25JbmRleCI6MSwibmFtZSI6IuW8oOS4iSIsImNvbklkIjoiNzEwMTEyMTk5MDDiha0xMjM0NVgiLCJleHAiOjE3MTI4MTA1NjV9.uhDO80b7gavDWhdkSxpH5crvmk48e8gGD67d5AswvWo
//        if(!StringUtils.hasLength(jwt)){
//            log.info("请求头token为空，返回未登录错误信息");
//            Result error = Result.erro("NOT_LOGIN");
//            String notLogin = JSONObject.toJSONString(error);
//            response.getWriter().write(notLogin);
//            return false;
//        }
        try {
//            Claims claims = JwtUtils.parseJWT(jwt);
            JwtUtils.parseJWT(jwt);
//            Result sucess = Result.success(claims);
//            String havLogin = JSONObject.toJSONString(sucess);
//            response.getWriter().write(havLogin);
        }catch (Exception e){

            e.printStackTrace();
            log.info("解析令牌失败，返回未登录错误信息");
            Result error = Result.erro("NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }
        log.info("令牌合法，放行");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandler.........");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterHandler...........");
    }
}
